var express = require("express");
var router = express.Router();
var path = require("path");
var yaml = require("yaml");
var randomstring = require("randomstring");
// var child_process = require("child_process");
var fs = require("fs");
const util = require("util");
const exec = util.promisify(require("child_process").exec);

const room_root = path.join(process.cwd(), "../room");
const room_config_root = path.join(room_root, "./configs");

async function initServer() {
    const files = fs.readdirSync(room_config_root);
    for (const file of files) {
        if (file === "readme.md") continue;
        
        const filePath = path.join(room_config_root, file);
        const str = fs.readFileSync(filePath, "utf-8");
        const server = yaml.parse(str);
        servers.push(server);
        await exec(`cd ${room_root} && pm2 start ${filePath}`);
    }
}
/**
 * type Server:
 * {
 *     id: "serverid",
 *     name: "国色天香",
 *     url: "ws://10.10.10.10:1234",
 * }
 */
const servers = [];
initServer();

/**
 * 服务器控制台
 */
router.get("/control", function (req, res, next) {
    return res.render("server");
});

/**
 * 获取完整服务器列表信息
 */
router.get("/control_list", function (req, res, next) {
    return res.json({ code: "0000", servers });
});

/**
 * 获取服务器列表
 */
router.get("/list", function (req, res, next) {
    const data = servers.map(({ id, name, ip, env: { port } }) => ({
        id,
        name,
        url: `ws://${ip}:${port}`,
    }));
    return res.json({ code: "0000", data });
});

/**
 * 注册游戏服务器
 */
router.post("/register", async function (req, res, next) {
    const { name, ip, port } = req.body;
    if (servers.find((item) => item.name === name || (item.ip === ip && item.port === port))) {
        return res.json({ code: "2001", message: "服务器名或者端口号重复" });
    }

    const id = randomstring.generate(7);
    const server = { id, name, ip, script: "./app.js", log: `./logs/${id}.log`, env: { port: Number(port) } };

    fs.writeFileSync(`${room_config_root}/${id}.yaml`, yaml.stringify(server), { encoding: "utf-8" });

    try {
        const { stderr, stdout } = await exec(`cd ${room_root} && pm2 start ./configs/${id}.yaml`);
        servers.push(server);
        return res.json({ code: "0000", message: "服务器已启动" });
    } catch (error) {
        console.log(error);
        return res.json({ code: "2002", message: "启动服务器失败" });
    }
});

/**
 * 注册游戏服务器
 */
router.post("/delete", async function (req, res, next) {
    const { id } = req.body;

    try {
        const filePath = `${room_config_root}/${id}.yaml`;
        const file = fs.readFileSync(filePath, "utf-8");
        const { name } = yaml.parse(file);
        const { stderr, stdout } = await exec(`pm2 delete ${name}`);
        fs.rmSync(filePath);
        const index = servers.findIndex((item) => item.id === id);
        if (index > -1) {
            servers.splice(index, 1);
        }
        return res.json({ code: "0000", message: "服务器已删除" });
    } catch (error) {
        console.log(error);
        return res.json({ code: "2003", message: "删除服务器失败" });
    }
});

module.exports = router;
